import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import MainLayout from '@/layout/MainLayout.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    component: MainLayout,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Index.vue'),
        meta: {
          title: '首页',
          requiresAuth: true
        }
      },
      {
        path: '/clan',
        name: 'Clan',
        component: () => import('@/views/clan/Index.vue'),
        meta: {
          title: '家族管理',
          requiresAuth: true
        }
      },
      {
        path: '/branch',
        name: 'Branch',
        component: () => import('@/views/branch/Index.vue'),
        meta: {
          title: '分支管理',
          requiresAuth: true
        }
      },
      {
        path: '/member',
        name: 'Member',
        component: () => import('@/views/member/Index.vue'),
        meta: {
          title: '成员管理',
          requiresAuth: true
        }
      },
      {
        path: '/spouse',
        name: 'Spouse',
        component: () => import('@/views/spouse/Index.vue'),
        meta: {
          title: '配偶管理',
          requiresAuth: true
        }
      },
      {
        path: '/familytree',
        name: 'FamilyTree',
        component: () => import('@/views/familytree/Index.vue'),
        meta: {
          title: '家族树',
          requiresAuth: true
        }
      },
      {
        path: '/audit',
        name: 'Audit',
        component: () => import('@/views/audit/Index.vue'),
        meta: {
          title: '审核管理',
          requiresAuth: true
        }
      },
      {
        path: '/familynews',
        name: 'FamilyNews',
        component: () => import('@/views/familynews/Index.vue'),
        meta: {
          title: '家族动态',
          requiresAuth: true
        }
      },
      {
        path: '/system',
        name: 'System',
        component: () => import('@/views/system/Index.vue'),
        meta: {
          title: '系统管理',
          requiresAuth: true
        }
      },
      {
        path: '/system/user',
        name: 'SystemUser',
        component: () => import('@/views/system/User.vue'),
        meta: {
          title: '用户管理',
          requiresAuth: true
        }
      },
      {
        path: '/system/role',
        name: 'SystemRole',
        component: () => import('@/views/system/Role.vue'),
        meta: {
          title: '角色管理',
          requiresAuth: true
        }
      },
      {
        path: '/system/menu',
        name: 'SystemMenu',
        component: () => import('@/views/system/Menu.vue'),
        meta: {
          title: '菜单管理',
          requiresAuth: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫 - 目标路径:', to.path);
  console.log('路由守卫 - 是否已登录:', store.getters.isLoggedIn);
  console.log('路由守卫 - 用户信息:', store.getters.userInfo);
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 陈氏族谱管理系统` : '陈氏族谱管理系统'
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 检查是否已登录
    const isLoggedIn = store.getters.isLoggedIn
    
    if (!isLoggedIn) {
      // 检查是否有token
      const token = localStorage.getItem('accessToken')
      console.log('路由守卫 - 检查token:', token);
      
      if (token) {
        try {
          // 检查用户信息是否已存在
          if (!store.getters.userInfo) {
            console.log('路由守卫 - 尝试获取用户信息');
            // 尝试获取用户信息
            await store.dispatch('getCurrentUser')
          }
          console.log('路由守卫 - 认证通过，允许访问');
          next()
        } catch (error) {
          console.error('获取用户信息失败:', error)
          // 清除无效的token
          store.commit('clearAuth')
          next('/login')
        }
      } else {
        // 没有token，跳转到登录页
        console.log('路由守卫 - 没有token，跳转到登录页');
        next('/login')
      }
    } else {
      // 已登录，直接通过
      console.log('路由守卫 - 已登录，直接通过');
      next()
    }
  } else {
    // 不需要认证的页面
    if (to.path === '/login' && store.getters.isLoggedIn) {
      // 已登录用户访问登录页，跳转到首页
      console.log('路由守卫 - 已登录用户访问登录页，跳转到首页');
      next('/')
    } else {
      console.log('路由守卫 - 不需要认证的页面');
      next()
    }
  }
})

export default router
